package com.inhim.pjhim.dowloadfile.ui;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.MainThread;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.inhim.pjhim.R;
import com.inhim.pjhim.app.BaseActivity;
import com.inhim.pjhim.dowloadfile.adapter.BaseRecyclerViewAdapter;
import com.inhim.pjhim.dowloadfile.adapter.DownloadListAdapter;
import com.inhim.pjhim.dowloadfile.adapter.provider.DownloadingProvider;
import com.inhim.pjhim.dowloadfile.download.DownloadInfo;
import com.inhim.pjhim.dowloadfile.download.MyBusinessInfoDid;
import com.inhim.pjhim.dowloadfile.download.limit.DownloadLimitManager;
import com.inhim.pjhim.entity.DownloadListLable;
import com.inhim.pjhim.http.Urls;
import com.inhim.pjhim.utils.FileUtils;
import com.inhim.pjhim.view.BToast;
import com.inhim.pjhim.view.CenterDialog;
import com.inhim.pjhim.view.XLinearLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * How to use Android Downloader in RecyclerView.
 */
public class ListActivity extends BaseActivity implements View.OnClickListener,
        BaseRecyclerViewAdapter.OnItemClickListener, DownloadingProvider.NotifyDataSetChanged {

    private TextView tvCourse, tv_edit;
    private ImageView iv_back;
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private RecyclerView recyclerView;
    //private LimitDownloadAdapter downloadListAdapter;
    private DownloadListAdapter downloadListAdapter;
    private TextView tvFile;
    private boolean isCheck;
    private LinearLayout lin_caozuo;
    private TextView textview1, textview2;
    private CenterDialog centerDialog;
    private ExecutorService mLimitThreadPool;
    private List<DownloadInfo> downloadInfoList;
    private List mAdapterList = new ArrayList();
    public static final int RsultCode = 100;
    private boolean mIsAll;

    @Override
    public Object offerLayout() {
        return R.layout.activity_list;
    }

    @Override
    public void onBindView() {
        mLimitThreadPool = Executors.newFixedThreadPool(2);
        EventBus.getDefault().register(this);
        downloadInfoList = getDownloadListData();
        for (int i = 0; i < downloadInfoList.size(); i++) {
            mDeviceHeaderMap.put(i, false);
        }
        initView();
    }

    @Override
    public void destory() {
        EventBus.getDefault().unregister(this);
    }

    public void initView() {
        recyclerView = findViewById(R.id.rv);
        initData();
        initAdapter();
        iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);
        tvCourse = findViewById(R.id.tvCourse);
        tvCourse.setText("下载管理");
        tv_edit = findViewById(R.id.tv_edit);
        tv_edit.setOnClickListener(this);
        // 取消item刷新的动画
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        lin_caozuo = findViewById(R.id.lin_caozuo);
        tvFile = findViewById(R.id.tvFile);
        textview1 = findViewById(R.id.textview1);
        textview2 = findViewById(R.id.textview2);
        textview1.setOnClickListener(v -> {
            for (int i = 0; i < downloadInfoList.size(); i++) {
                mDeviceHeaderMap.put(i, true);
            }
            mIsAll = true;
            downloadListAdapter.setCheck(true, mDeviceHeaderMap);
            downloadListAdapter.notifyDataSetChanged();
        });
        textview2.setOnClickListener(v -> setDiaglog());
        tvFile.setText("存储路径:" + Urls.getFilePath());
    }


    public void initData() {
        mAdapterList.clear();
        downloadInfoList = getDownloadListData();
        mDeviceHeaderMap = new HashMap<>();
        for (int i = 0; i < downloadInfoList.size(); i++) {
            mDeviceHeaderMap.put(i, false);
        }
        if (downloadInfoList != null && downloadInfoList.size() > 0) {
            mAdapterList.addAll(downloadInfoList);
        }
        setHaveAdapterDate();
       /* if (downloadListAdapter != null) {
            int size = mAdapterList.size();
            downloadListAdapter.notifyItemRangeChanged(0, size);

        }*/
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //这里对UI界面进行操作
                if (downloadListAdapter != null) {
                    downloadListAdapter.setCheck(false, mDeviceHeaderMap);
                    downloadListAdapter.notifyDataSetChanged();
                }
            }
        });
        //downloadListAdapter = new LimitDownloadAdapter(ListActivity.this,downloadInfoList);

    }

    private void initAdapter() {
        downloadListAdapter = new DownloadListAdapter(mAdapterList, ListActivity.this);
        if (downloadListAdapter.getDownloadingProvider() != null) {
            downloadListAdapter.getDownloadingProvider().setNotifyDataSetChanged(this);
        }
        recyclerView.setLayoutManager(new XLinearLayoutManager(ListActivity.this));
        recyclerView.setAdapter(downloadListAdapter);
        downloadListAdapter.setOnItemClickListener((baseQuickAdapter, view, i) -> {
            if (downloadListAdapter.getData().get(i) instanceof DownloadListLable) {
                DownloadListLable downloadListLables = (DownloadListLable) downloadListAdapter.getData().get(i);
                Intent intent = new Intent(ListActivity.this, HaveDownloadListActivity.class);
                intent.putExtra("type", downloadListLables.getType());
                intent.putExtra("Title", downloadListLables.getTitle());
                startActivityForResult(intent, RsultCode);
            }
        });
    }

    private List<DownloadInfo> getDownloadListData() {
        try {
            List<DownloadInfo> myBusinessInfos = LitePal.findAll(DownloadInfo.class);
            return myBusinessInfos;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private void setHaveAdapterDate() {
        List<MyBusinessInfoDid> haveDownloadList = getHaveDownloadListData();
        List<MyBusinessInfoDid> radioHaveDownloadList = new ArrayList<>();
        List<MyBusinessInfoDid> videoHaveDownloadList = new ArrayList<>();
        long radioTotal = 0;
        long videoTotal = 0;
        if (haveDownloadList != null && haveDownloadList.size() > 0) {
            DownloadListLable radioList = new DownloadListLable();
            DownloadListLable videoList = new DownloadListLable();
            for (int i = 0; i < haveDownloadList.size(); i++) {
                if (haveDownloadList.get(i).getType().equals("3")) {
                    radioHaveDownloadList.add(haveDownloadList.get(i));
                    radioTotal += haveDownloadList.get(i).getTotal();
                } else if (haveDownloadList.get(i).getType().equals("2")) {
                    videoHaveDownloadList.add(haveDownloadList.get(i));
                    videoTotal += haveDownloadList.get(i).getTotal();
                }
            }
            if (radioHaveDownloadList.size() > 0) {
                radioList.setCover(radioHaveDownloadList.get(0).getCover());
                radioList.setNum(radioHaveDownloadList.size() + "个音频");
                try {
                    double stringBuilder = 0;
                    for (int i = 0; i < radioHaveDownloadList.size(); i++) {
                        String size = FileUtils.getAutoFileOrFilesSize(radioHaveDownloadList.get(i).getFilePath());
                        String strSize="0.00";
                        try {
                            strSize=formateRate(size);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        if("0B".equals(strSize)){
                            strSize="0.00";
                        }
                        stringBuilder += Double.valueOf(strSize);
                    }
                    //radioList.setFilreSize(FileUtil.formatFileSize(radioTotal));
                    if (stringBuilder > 1024) {
                        BigDecimal b = new BigDecimal(stringBuilder / 1024);
                        double df = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        radioList.setFilreSize(df + "G");
                    } else {
                        BigDecimal b = new BigDecimal(stringBuilder);
                        double df = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        radioList.setFilreSize(df + "M");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    radioList.setFilreSize("0B");
                }
                radioList.setType("3");
                radioList.setTitle("已下载聆听");
            } else {
                radioList.setCover("");
                radioList.setNum("0个音频");
                radioList.setFilreSize("0M");
                radioList.setType("3");
                radioList.setTitle("已下载聆听");
            }

            if (videoHaveDownloadList.size() > 0) {
                videoList.setCover(videoHaveDownloadList.get(0).getCover());
                videoList.setNum(videoHaveDownloadList.size() + "个视频");
                try {
                    double stringBuilders = 0;
                    for (int i = 0; i < videoHaveDownloadList.size(); i++) {
                        String size = FileUtils.getAutoFileOrFilesSize(videoHaveDownloadList.get(i).getFilePath());
                        String strSize="0.00";
                        try {
                            strSize=formateRate(size);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                        stringBuilders += Double.valueOf(strSize);
                    }
                    //radioList.setFilreSize(FileUtil.formatFileSize(radioTotal));
                    if (stringBuilders > 1024) {
                        BigDecimal b = new BigDecimal(stringBuilders / 1024);
                        double df = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        videoList.setFilreSize(df + "G");
                    } else {
                        BigDecimal b = new BigDecimal(stringBuilders);
                        double df = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        videoList.setFilreSize(df + "M");
                    }
                } catch (Exception e) {
                    videoList.setFilreSize("0B");
                    e.printStackTrace();
                }
                //videoList.setFilreSize(FileUtil.formatFileSize(videoTotal));
                videoList.setType("2");
                videoList.setTitle("已下载视频");
            } else {
                videoList.setCover("");
                videoList.setNum("0个视频");
                videoList.setFilreSize("0M");
                videoList.setType("2");
                videoList.setTitle("已下载视频");
            }
            if (videoList.getCover() != null) {
                mAdapterList.add(videoList);
            }
            if (radioList.getCover() != null) {
                mAdapterList.add(radioList);
            }
        } else {
            DownloadListLable radioList = new DownloadListLable();
            DownloadListLable videoList = new DownloadListLable();
            radioList.setCover("");
            radioList.setNum("0个音频");
            radioList.setFilreSize("0M");
            radioList.setType("3");
            radioList.setTitle("已下载聆听");
            videoList.setCover("");
            videoList.setNum("0个视频");
            videoList.setFilreSize("0M");
            videoList.setType("2");
            videoList.setTitle("已下载视频");
            if (videoList.getCover() != null) {
                mAdapterList.add(videoList);
            }
            if (radioList.getCover() != null) {
                mAdapterList.add(radioList);
            }
        }
    }

    public String formateRate(String rateStr) {
        if (rateStr.indexOf(".") != -1) {
            //获取小数点的位置
            int num = 0;
            //找到小数点在字符串中的位置,找到返回一个int类型的数字,不存在的话返回 -1
            num = rateStr.indexOf(".");

            String dianAfter = rateStr.substring(0, num + 1);//输入100.30,dianAfter = 100.
            String afterData = rateStr.replace(dianAfter, "");//把原字符(rateStr)串包括小数点和小数点前的字符替换成"",最后得到小数点后的字符(不包括小数点)

            //判断小数点后字符的长度并做不同的操作,得到小数点后两位的字符串
            if (afterData.length() < 2) {
                afterData = afterData + "0";
            } else {
                afterData = afterData;
            }
            //返回元字符串开始到小数点的位置 + "." + 小数点后两位字符
            return rateStr.substring(0, num) + "." + afterData.substring(0, 2);
        } else {
            if (rateStr == "1") {
                return "100";
            } else {
                return rateStr;
            }
        }
    }

    private List<MyBusinessInfoDid> getHaveDownloadListData() {
        List<MyBusinessInfoDid> myBusinessInfos = LitePal.findAll(MyBusinessInfoDid.class);
        if (myBusinessInfos.size() > 0) {
        }
        return myBusinessInfos;
    }

    private Map<Integer, Boolean> mDeviceHeaderMap = new HashMap<>();
    private MyTask mTask;
    private void setDiaglog() {
        View outerView = LayoutInflater.from(ListActivity.this).inflate(R.layout.dialog_deletes, null);
        Button btn_ok = outerView.findViewById(R.id.btn_ok);
        Button btn_cancel = outerView.findViewById(R.id.btn_cancel);
        btn_ok.setOnClickListener(v -> {
            centerDialog.dismiss();
            /*int count=recyclerView.getAdapter().getItemCount();
            for (int i = 0; i < count; i++) {
                ConstraintLayout layout= (ConstraintLayout) recyclerView.getLayoutManager().findViewByPosition(i);
                if(layout!=null){
                    CheckBox checkBox = layout.findViewById(R.id.checkbox);
                    if(checkBox!=null){
                        mDeviceHeaderMap.put(i, checkBox.isChecked());
                    }
                }
            }*/
           /* if (mIsAll) {
                deleteAllFiles();
            } else {
                deleteFiles(mDeviceHeaderMap);
            }*/
            showLoading("删除中");
            if(mTask!=null){
                mTask.cancel(true);
            }
            mTask = new MyTask(mIsAll);
            mTask.execute();
        });
        btn_cancel.setOnClickListener(v -> centerDialog.dismiss());
        //防止弹出两个窗口
        if (centerDialog != null && centerDialog.isShowing()) {
            return;
        }

        centerDialog = new CenterDialog(ListActivity.this, R.style.ActionSheetDialogBotoomStyle);
        //将布局设置给Dialog
        centerDialog.setContentView(outerView);
        centerDialog.show();//显示对话框
    }

    @Override
    protected void onPause() {
        super.onPause();
        //如果异步任务不为空 并且状态是 运行时  ，就把他取消这个加载任务
        if(mTask !=null && mTask.getStatus() == AsyncTask.Status.RUNNING){
            mTask.cancel(true);
        }
    }

    /**
     * 步骤1：创建AsyncTask子类
     * 注：
     * a. 继承AsyncTask类
     * b. 为3个泛型参数指定类型；若不使用，可用java.lang.Void类型代替
     * c. 根据需求，在AsyncTask子类内实现核心方法
     */

    private class MyTask extends AsyncTask<String, Integer, String> {
        // 方法1：onPreExecute（）
        // 作用：执行 线程任务前的操作
        // 注：根据需求复写
        private boolean isBoolean;
        private String status = "over";

        public MyTask(Boolean isBoolean) {
            super();
            this.isBoolean = isBoolean;
        }

        @Override
        protected void onPreExecute() {

        }

        // 方法2：doInBackground（）
        // 作用：接收输入参数、执行任务中的耗时操作、返回 线程任务执行的结果
        // 注：必须复写，从而自定义线程任务
        @Override
        protected String doInBackground(String... params) {
            // 自定义的线程任务
            // 可调用publishProgress（）显示进度, 之后将执行onProgressUpdate（）
            if (isBoolean) {
                deleteAllFiles();
            } else {
                deleteFiles(mDeviceHeaderMap);
            }
            return status;
        }

        // 方法3：onProgressUpdate（）
        // 作用：在主线程 显示线程任务执行的进度
        // 注：根据需求复写
        @Override
        protected void onProgressUpdate(Integer... progresses) {

        }
        // 方法4：onPostExecute（）
        // 作用：接收线程任务执行结果、将执行结果显示到UI组件
        // 注：必须复写，从而自定义UI操作

        @Override
        protected void onPostExecute(String result) {
            if (status.equals(result)) {
                hideLoading();
                lin_caozuo.setVisibility(View.GONE);
                isCheck = false;
            }
            // UI操作
        }

        // 方法5：onCancelled()
        // 作用：将异步任务设置为：取消状态
        @Override

        protected void onCancelled() {
            hideLoading();
        }

    }

    public void deleteAllFiles() {
        for (int i = 0; i < downloadInfoList.size(); i++) {
            try {
                //FileUtils.deleteFiles(downloadInfoList.get(i).getFilePath());
               File file = new File(downloadInfoList.get(i).getFilePath());
                FileUtils.deleteOrFiles(file);
                 /*if (file.exists()) {
                    file.delete();
                }*/
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                DownloadLimitManager.getInstance().cancelDownload(downloadInfoList.get(i));
                downloadInfoList.get(i).delete();
                downloadInfoList.remove(i);
                downloadInfoList.get(i).delete();
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
        initData();
    }

    public void deleteFiles(Map<Integer, Boolean> deleteMap) {
        showLoading("删除中");
        for (int i = 0; i < deleteMap.size(); i++) {
            if (deleteMap.get(i)) {
                try {
                    //FileUtils.deleteFiles(downloadInfoList.get(i).getFilePath());
                    File file = new File(downloadInfoList.get(i).getFilePath());
                    FileUtils.deleteOrFiles(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    DownloadLimitManager.getInstance().cancelDownload(downloadInfoList.get(i));
                    /*downloadInfoList.get(i).delete();
                    downloadInfoList.remove(i);*/
                    downloadInfoList.get(i).delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        initData();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_edit:
                if (!isCheck) {
                    isCheck = true;
                    downloadListAdapter.setCheck(isCheck, mDeviceHeaderMap);
                    downloadListAdapter.notifyDataSetChanged();
                    lin_caozuo.setVisibility(View.VISIBLE);
                } else {
                    isCheck = false;
                    downloadListAdapter.setCheck(isCheck, mDeviceHeaderMap);
                    downloadListAdapter.notifyDataSetChanged();
                    lin_caozuo.setVisibility(View.GONE);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(int position) {

    }

    public void updateProgress(DownloadInfo info) {
        for (int i = 0; i < mAdapterList.size(); i++) {
            if ((DownloadInfo) mAdapterList.get(i) instanceof DownloadInfo) {
                DownloadInfo downloadInfo = (DownloadInfo) mAdapterList.get(i);
                if (downloadInfo.getUrl().equals(info.getUrl())) {
                    mAdapterList.set(i, info);
                    downloadListAdapter.notifyItemChanged(i);
                    break;
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void update(DownloadInfo info) {
        if (DownloadInfo.DOWNLOAD.equals(info.getDownloadStatus())) {
            updateProgress(info);
        } else if (DownloadInfo.DOWNLOAD_OVER.equals(info.getDownloadStatus())) {
            updateProgress(info);
            initData();
        } else if (DownloadInfo.DOWNLOAD_PAUSE.equals(info.getDownloadStatus())) {
            updateProgress(info);
            BToast.showText("下载暂停");
        } else if (DownloadInfo.DOWNLOAD_CANCEL.equals(info.getDownloadStatus())) {

            updateProgress(info);
            //BToast.showText("下载取消");
        } else if (DownloadInfo.DOWNLOAD_WAIT.equals(info.getDownloadStatus())) {

            updateProgress(info);
            BToast.showText("等待下载");

        } else if (DownloadInfo.DOWNLOAD_ERROR.equals(info.getDownloadStatus())) {
            updateProgress(info);
            BToast.showText("下载出错");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RsultCode == resultCode) {
            initData();
        }
    }

    @Override
    public void notifyChanged() {
        initData();
    }

    @Override
    public void checkOnClick(boolean isCheck, int position) {
        if (!isCheck) {
            mIsAll = false;
        }
        mDeviceHeaderMap.put(position, isCheck);
    }
}
